<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2021/5/24
 * Time: 16:41
 */

namespace App\Services\Gather;


use App\Patent;
use App\PatentTemp;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Ramsey\Uuid\Uuid;

class IPRVCService
{
    protected function client()
    {
        return new Client([
            'base_uri' => 'https://www.iprvc.top/',
            'timeout'  => 2.0,
        ]);
    }
    protected function header()
    {
        return [
            ':scheme'=>'https',
            'Content-Type' => 'application/x-www-form-urlencoded',
            'referer'=>'https://www.iprvc.top/cost_info.php',
            'accept'=>'application/json, text/javascript, */*; q=0.01',
            'user-agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
            'cookie'=>'PHPSID='.Uuid::uuid1()->getHex()->toString()
        ];
    }

    public function detail($patent_sn)
    {
        $data = array();
        $data['patent_sn'] = $this->base64($patent_sn);
        try{
            $response = $this->client()->requestAsync('POST','cost_info.php?act=search_patent',[
                'headers' => $this->header(),
                'form_params' => $data,
            ]);
            $response->then(
                function (ResponseInterface $res) {
                    dump(json_decode($res->getBody()->getContents(), true));
                    echo $res->getStatusCode() . "\n";
                },
                function (RequestException $e) {
                    echo $e->getMessage() . "\n";
                    echo $e->getRequest()->getMethod();
                }
            );
            $response->wait();
            return 'ok11';
        }catch (\Exception $exception){
            return $exception->getMessage();
        }
    }
    public function sync(PatentTemp $patent)
    {
        $data['patent_sn'] = $this->base64($patent->patent_sn);
        try{
            $response = $this->client()->request('POST','cost_info.php?act=search_patent',[
                'headers' => $this->header(),
                'form_params' => $data,
            ]);
            $data = json_decode($response->getBody()->getContents(), true);
            if(isset($data['patentinfo'])){
                $this->updatePatent($patent,$data);
            }
            echo $patent->id.'---'.$patent->patent_sn."-ok\n";
        }catch (\Exception $exception){
            echo  $patent->patent_sn.'---'.$exception->getMessage()."\n";
        }
    }
    public function updatePatent(PatentTemp $patent,$data)
    {
        if(!isset($data['patentinfo'])){
            return false;
        }
        if(!$data['patentinfo']){
            $patent->update(['state'=>1]);
        }
        return $patent->update([
           'info'=>[
               'apply_date'=>$data['patentinfo']['apply_date'],
               'ipc_main'=>$data['patentinfo']['main_number'],
               'legal_status'=>$data['patentinfo']['status'],
               'applicant'=>$data['patentinfo']['apply_name'],
               'inventor'=>$data['patentinfo']['inventor'],
               'agency'=>$data['patentinfo']['agency'],
               'agent'=>$data['patentinfo']['agent'],
           ],
            'djf'=>collect($data['djf'])->map(function($item){
                    return [
                        'name'=>$item['cost_type'],
                        'amount'=>$item['payment_amount'],
                        'last_time'=>$item['ent_time'],
                    ];
            })->all(),
            'yjf'=>collect($data['yjf'])->map(function($item){
                return [
                    'name'=>$item['cost_type'],
                    'amount'=>$item['payment_amount'],
                    'payer'=>$item['fee_status'],
                    'pay_time'=>$item['ent_time'],
                    'bill_number'=>$item['receipt_number'],
                ];
            })->all(),
            'state'=>1
        ]);
    }

    private function base64($str)
    {
        $str = strtr($str,array('C'=>'','c'=>'','N'=>'','n'=>'','.'=>'',' '=>''));
        $_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        $output = "";
        $arr = str_split($str, 3);
        foreach ($arr as $value) {
            $chr1 = ord($value[0]);
            $chr2 = isset($value[1])?ord($value[1]):null;
            $chr3 = isset($value[2])?ord($value[2]):null;
            $enc1 = $chr1 >> 2;
            $enc2 = (($chr1 & 3) << 4) | ($chr2 >> 4);
            $enc3 = (($chr2 & 15) << 2) | ($chr3 >> 6);
            $enc4 = $chr3 & 63;
            if(!is_numeric($chr2)){
                $enc3 = $enc4 = 64;
            }elseif (!is_numeric($chr3)){
                $enc4 = 64;
            }
            $output=$output.substr($_keyStr,$enc1,1).substr($_keyStr,$enc2,1).substr($_keyStr,$enc3,1).substr($_keyStr,$enc4,1);
        }
        return $output;
    }
}